package com.newway.common.utils;

import com.alibaba.fastjson.JSON;
import com.newway.common.login.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class JwtTokenUtil {

    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtil.class);

    @Resource
    StringRedisTemplate stringRedisTemplate;

    // 令牌秘钥
    @Value("${jwt.token.secret}")
    private String secret;

    @Value("${jwt.token.expireTime}")
    private long expireTime;

    @Value("${jwt.token.refreshTime}")
    private long refreshTime;


    /**
     * 生成token
     * @param loginUser
     * @return
     */
    public String createToken(LoginUser loginUser){
        String uuid = UUID.randomUUID().toString().replace("-","");
        loginUser.setUuid(uuid);
        refreshToken(loginUser);
        Map<String, Object> claims = new HashMap<>();
        claims.put("login_user_key", uuid);
        claims.put("subject", loginUser.getUserName());
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(loginUser.getUserName())
                //.setIssuedAt(new Date(System.currentTimeMillis()))
                //.setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY))
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    private SecretKey getSigningKey() {
        return Keys.hmacShaKeyFor(secret.getBytes());
    }

    public LoginUser getLoginUser(HttpServletRequest request){
        String token = getToken(request);
        if(StringUtils.isNotBlank(token)){
            try {
                Claims claims = parseToken(token);
                String uuid = (String) claims.get("login_user_key");
                String loginKey = loginKey(uuid);
                String res = stringRedisTemplate.opsForValue().get(loginKey);
                LoginUser user = JSON.parseObject(res,LoginUser.class);
                return user;
            }catch (Exception e){
                log.error("获取用户信息异常'{}'", e.getMessage());
            }
        }
        return null;
    }

    /**
     * 获取token
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(StringUtils.isNotBlank(token) && token.startsWith("Bearer ")){
            token = token.replace("Bearer ","");
        }
        return token;
    }


    /**
     * 解析token
     * @param token
     * @return
     */
    private Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 存放redis中的登录key
     * @param uuid
     * @return
     */
    private String loginKey(String uuid){
        return "login_token_"+uuid;
    }

    /**
     * 刷新token，修改用户信息后，可调用该方法
     * @param loginUser
     */
    public void refreshToken(LoginUser loginUser){
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime);
        //更新redis用户缓存信息
        String loginKey = loginKey(loginUser.getUuid());
        stringRedisTemplate.opsForValue().set(loginKey,JSON.toJSONString(loginUser), expireTime, TimeUnit.MILLISECONDS);
    }

    /**
     * 校验token是否即将过期
     * @param loginUser
     */
    public void verifyToken(LoginUser loginUser){
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= refreshTime) {
            refreshToken(loginUser);
        }
    }
}